<template> 
    <transition :name="direction" mode="out-in">
      <!-- <scale-box :width="1920" :height="1080" :bgc="currentTheme!='customDarkTheme'?'transparent':''" :delay="100" :isFlat="false"> -->
        <router-view/>
        <!--  
        <router-view v-slot="{ Component }">
          <transition> 
              <component :is="Component" /> 
          </transition>
        </router-view> -->
      <!-- <v-snackbar v-model="msg" v-if="msg"
        :timeout="2000"
        color="primary"
        variant="tonal"
      > 
      <div v-if="msg">{{msg}}</div>
      </v-snackbar>  -->
   <!-- </scale-box> -->
    </transition>
</template>
<script setup> 
// import { useTheme } from 'vuetify'
import { getCurrentInstance,ref, onMounted,onActivated, onBeforeUnmount, computed,watch,provide } from 'vue';
import { useUserStore } from './stores/user'
import { useThemeStore } from './stores/theme'
import { useLicenseStore } from './stores/license'
import { log } from './api' 
import { getOrgConfigData } from './api/api' 
import axios from 'axios'
const busInstance = getCurrentInstance()
const userStore = useUserStore() 
const licenseStore = useLicenseStore()
const msg = ref(''); 
async function startShow(){ 
  if(!window.electronAPI){
    return;
  }
  const appInfo = await window.electronAPI.getAppInfo() 
  if(appInfo){ 
      let orgId="";
      if(userStore.orgId){
        orgId=userStore.orgId;
      }
      let appInfoJSON=JSON.parse(appInfo);
      if(appInfoJSON.id){
         userStore.setClientId(appInfoJSON.id)
      }
      log({name:"进入主界面",appInfo:appInfoJSON,orgId:orgId}).then(res => {
        if(res.code=='200'&&res.data){ 
        } 
      })
  } 
}
let storageUser=null;
async function getMyStoreUserData(){ 
  if(!window.electronAPI){ 
    return;
  }
  //用户的数据
  const userInfo = await window.electronAPI.getUserInfo() 
  if(userInfo){
    storageUser= JSON.parse(userInfo);
    if(storageUser&&storageUser.orgId){
      userStore.setOrgId(storageUser.orgId)
    }
    if(storageUser&&storageUser.apiHost){
      userStore.setApiHost(storageUser.apiHost)
    }
    if(storageUser&&storageUser.agent){
      userStore.setAgent(storageUser.agent)
    }
    if(storageUser&&storageUser.outputDeviceId){
      userStore.setOutputDeviceId(storageUser.outputDeviceId)
    }
    //如果没有默认那么自动设置一个默认的数据
    if(storageUser&&storageUser.themeUrl){
      const themeStore= useThemeStore()
      if(!themeStore.themeUrl){
         themeStore.setThemeUrl(storageUser.themeUrl)
      }
    } 
    if(storageUser&&storageUser.token&&licenseStore.auth){
      userStore.setUserToken(storageUser.token)
      userStore.setOrgId(storageUser.orgId)
      setTimeout(function(){
       let data = userStore.getUserInfoData();
       if(!data){ 
          window.electronAPI.setUserInfo({orgId:""})
       }
      },1000) 
    } 
  } 
  //离线
  // getStaticThemeCacheData('zsb');
  //在线
  // getOnlineThemeCacheData('zsb');
  //离线
  // getThemeCacheData('zsb');
   try {
    if(window.electronAPI){  
       if(storageUser&&storageUser.key){
        getOnlineThemeCacheData(storageUser.key); 
       }
    }
  } catch (error) {} 
} 
let themeData = {};
//在线的静态主题数据
function getOnlineThemeCacheData(theme){
  //获取主题缓存的数据 
  getOrgConfigData({key:theme}).then((res) =>{
    if(res.code=='200'&&res.data){ 
      themeData=res.data;
      const themeStore= useThemeStore()
      if(themeData.theme){
        themeStore.setTheme(themeData.theme)
         themeStore.setThemeData(themeData[theme]) 
      } 
      themeStore.setThemeUrl(themeData.themeUrl)
      if(userStore.themeCache){
        setThemeCacheData(themeData);
      } 
    }
  })
  .catch((err) => { 
    if(userStore.themeCache){
      getThemeCacheData(theme);
    }
  }); 
} 
let themeCacheTempPath='//themeCache.json'
//离线的主题数据缓存
async function setThemeCacheData(data){ 
  try {
    await window.electronAPI.setTempFilePathInfo(themeCacheTempPath,data).then((res) =>{
    }) 
  } catch (error) {} 
} 
//离线的主题数据
function getThemeCacheData(theme){ 
  let promiseList = [];  
  if(JSON.stringify(themeData)=="{}"&&window.electronAPI){ 
    const promise = window.electronAPI.getTempFilePathInfo(themeCacheTempPath).then((res) =>{
        themeData = JSON.parse(res)
    })
    promiseList.push(promise);
  }
  Promise.all(promiseList)
  .then(() => {  
    const themeStore= useThemeStore()
    themeStore.setTheme(themeData.theme)
    themeStore.setThemeData(themeData[theme]) 
    themeStore.setThemeUrl(themeData.themeUrl)
  })
  .catch((err) => {
    console.error("Theme错误", err);
  }); 
} 
//静态的静态主题数据
function getStaticThemeCacheData(theme){
  //获取主题缓存的数据
  let str='//theme//'+theme+'.json'
  let promiseList = []; 
  const promise = axios.get('/theme/'+theme+'.json').then((res) => { 
    themeData = res.data;  
  })  
  if(JSON.stringify(themeData)!="{}"&&window.electronAPI){ 
    const dd = window.electronAPI.getFilePathInfo(str).then((res) =>{
        themeData = JSON.parse(res)
    })
    promiseList.push(dd); 
  }else{
    promiseList.push(promise);
  }
  Promise.all(promiseList)
  .then(() => { 
    const themeStore= useThemeStore()
    themeStore.setTheme(themeData.theme)
    themeStore.setThemeData(themeData[theme]) 
  })
  .catch((err) => {
    console.error("Theme错误", err);
  }); 
} 
onMounted(() => {
  // getMyStoreUserData()
  switch (performance.navigation.type) {
    case 0:
      // let remote=ipcRenderer.remote;
      // if(remote){ 
      //   console.log(remote.getGlobal("sharedObject"));
      // }  
      getMyStoreUserData()
      setTimeout(function(){
        startShow();
      },Math.random()*3000) 
      console.log("首次加载出来了");  
      break;
    case 1:
        console.log("页面刷新完了");
        console.log(storageUser);
        if(userStore.token){
           getMyStoreUserData()
        }
      break;
  }
  //jianrong web 
  // const theme = useTheme()
  // let currentTheme=theme.global.name.value
  // if(userStore&&userStore.theme){
  //   currentTheme=userStore.theme
  //   theme.global.name.value=currentTheme
  // }
  // setSystemTheme(currentTheme);
  // userStore.setTheme(currentTheme); 
});

function setSystemTheme(theme){
  if(theme=='customLightTheme'){
    document.querySelector('body').setAttribute('style',"background:rgba(0,0,0,1);")
    // document.querySelector('body').setAttribute('style', 'background:-webkit-linear-gradient(90deg, #6559b6,#861f5e,#630910);background: linear-gradient(90deg, #6559b6,#861f5e,#630910);')
  }else{
    // document.querySelector('body').removeAttribute('style')background:rgb(var(--v-theme-background))
    document.querySelector('body').setAttribute('style',"background:rgba(0,0,0,1);")
  }
  if(window.electronAPI){
    let param='light'
    if(theme=='customDarkTheme'){
      param='dark'
    }
    window.electronAPI.setNativeTheme(param);
  }
}
busInstance?.proxy?.$Bus.on('SystemThemeChange', function(data){
  setSystemTheme(data)
})
busInstance?.proxy?.$Bus.on('SystemInfoMsg', function(data){
   msg.value=data.msg
})
</script> 
<style lang="scss">  
html,body{
  margin:0; 
  width: 100vw;
  height: 100vh;
  // overflow: hidden;                                            
}
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

nav {
  padding: 30px;
}

nav a {
  font-weight: bold;
  color: #2c3e50;
}

nav a.router-link-exact-active {
  color: #42b983;
}
html {
  overflow:auto
}
blockquote,
body,
dd,
dl,
dt,
fieldset,
form,
input,
li,
ol,
p,
pre,
td,
th,
ul {
  font-weight:400;
  margin:0;
  padding:0
}
h1,
h2,
h3,
h4,
h5 {
  margin:0;
  padding:0
}
select {
  font-size:12px
}
table {
  border-collapse:collapse
}
fieldset,
img {
  border:0 none
}
fieldset {
  margin:0;
  padding:0
}
fieldset p {
  margin:0;
  padding:0 0 0 8px
}
legend {
  display:none
}
address,
caption,
em,
i,
strong,
th {
  font-style:normal;
  font-weight:400
}
table caption {
  margin-left:-1px
}
hr {
  border-bottom:1px solid #fff;
  border-top:1px solid #e4e4e4;
  border-width:1px 0;
  clear:both;
  height:2px;
  margin:5px 0;
  overflow:hidden
}
ol,
ul {
  list-style-image:none;
  list-style-position:outside;
  list-style-type:none
}
caption,
th {
  text-align:left
}
blockquote:after,
blockquote:before,
q:after,
q:before {
  content:””
}
 
.page-transition{
   &.active{
        &::before{
            visibility: visible;
            clip-path: circle(100%); 
        }
    }  
    &::before{
        display: block;
        position: fixed;
        top: 0;
        left: 0;
        content: '';
        width: 1920px;
        height: 1080px;
        background: rgba(0, 0, 0, 0.9);
        transition: all 500ms ease-in-out;
        clip-path: circle(20px at calc(50% - 10px) 1080px);
        visibility: hidden;
        z-index: 999;
    }
}
</style>
